import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import '../widgets/modern_sidebar.dart';
import '../widgets/note_list.dart';
import '../widgets/markdown_editor.dart';
import 'settings_screen.dart';
import '../utils/responsive_layout.dart';

/**
 * 主屏幕组件
 * 采用现代化设计和响应式布局，支持多端适配
 */
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  bool _isSidebarCollapsed = false;
  bool _isNoteListCollapsed = false;
  late AnimationController _layoutAnimationController;
  late Animation<double> _layoutAnimation;
  
  // 示例数据
  String? _selectedNoteId;
  final List<NoteItem> _notes = [
    NoteItem(
      id: '1',
      title: '欢迎使用 LinkBook',
      content: '# 开始写作\n\n这是您的第一个笔记，支持 **Markdown** 语法。\n\n## 功能特点\n\n- 支持 Markdown 编辑\n- 实时预览\n- 现代化界面\n- 响应式布局\n\n开始您的写作之旅吧！',
      createdAt: DateTime.now().subtract(const Duration(hours: 2)),
      updatedAt: DateTime.now().subtract(const Duration(minutes: 30)),
    ),
    NoteItem(
      id: '2',
      title: '示例笔记',
      content: '这是一个示例笔记内容，展示了笔记的基本功能。\n\n您可以在这里记录想法、制定计划或者保存重要信息。',
      createdAt: DateTime.now().subtract(const Duration(days: 1)),
      updatedAt: DateTime.now().subtract(const Duration(hours: 5)),
    ),
  ];

  @override
  void initState() {
    super.initState();
    _layoutAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _layoutAnimation = CurvedAnimation(
      parent: _layoutAnimationController,
      curve: Curves.easeInOut,
    );
    
    // 默认选中第一个笔记
    if (_notes.isNotEmpty) {
      _selectedNoteId = _notes.first.id;
    }
  }

  @override
  void dispose() {
    _layoutAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.surfaceLight,
      body: ResponsiveLayout(
        mobile: _buildMobileLayout(),
        tablet: _buildTabletLayout(),
        desktop: _buildDesktopLayout(),
      ),
    );
  }

  /**
   * 构建手机端布局
   */
  Widget _buildMobileLayout() {
    return Column(
      children: [
        _buildAppBar(),
        Expanded(
          child: _selectedNoteId != null
              ? _buildNoteEditor()
              : _buildNoteList(width: double.infinity),
        ),
      ],
    );
  }

  /**
   * 构建平板端布局
   */
  Widget _buildTabletLayout() {
    return Row(
      children: [
        _buildSidebar(width: 280),
        _buildNoteList(width: 300),
        Expanded(
          child: _buildNoteEditor(),
        ),
      ],
    );
  }

  /**
   * 构建桌面端布局
   */
  Widget _buildDesktopLayout() {
    return Row(
      children: [
        _buildSidebar(width: 300),
        _buildNoteList(width: 350),
        Expanded(
          child: _buildNoteEditor(),
        ),
      ],
    );
  }

  /**
   * 构建应用栏
   */
  Widget _buildAppBar() {
    return Container(
      height: 60,
      decoration: BoxDecoration(
        color: AppTheme.cardLight,
        border: Border(
          bottom: BorderSide(
            color: Colors.grey.shade300,
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          const SizedBox(width: 16),
          Text(
            'LinkBook',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: AppTheme.primaryColor,
            ),
          ),
          const Spacer(),
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              // TODO: 打开设置页面
            },
          ),
          const SizedBox(width: 16),
        ],
      ),
    );
  }

  /**
   * 构建侧边栏
   */
  Widget _buildSidebar({required double width}) {
    return ModernSidebar(
      onNewNote: () {
        // TODO: 实现新建笔记功能
      },
      onSettings: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => SettingsScreen(),
          ),
        );
      },
    );
  }

  /**
   * 构建文件夹项
   */
  Widget _buildFolderItem(String title, IconData icon, bool isSelected) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 2),
      decoration: BoxDecoration(
        color: isSelected ? AppTheme.primaryColor.withOpacity(0.1) : null,
        borderRadius: BorderRadius.circular(8),
      ),
      child: ListTile(
        leading: Icon(
          icon,
          size: 20,
          color: isSelected ? AppTheme.primaryColor : Colors.black54,
        ),
        title: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            color: isSelected ? AppTheme.primaryColor : Colors.black87,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
        onTap: () {
          // TODO: 选择文件夹
        },
      ),
    );
  }

  /**
   * 构建笔记列表
   */
  Widget _buildNoteList({required double width}) {
    return Container(
      width: width,
      decoration: BoxDecoration(
        color: AppTheme.cardLight,
        border: Border(
          right: BorderSide(
            color: AppTheme.borderColor,
            width: 1,
          ),
        ),
      ),
      child: NoteList(
        notes: _notes,
        selectedNoteId: _selectedNoteId,
        onNoteSelected: (noteId) {
          setState(() {
            _selectedNoteId = noteId;
          });
        },
        onNewNote: () {
          // TODO: 实现新建笔记功能
        },
      ),
    );
  }

  /**
   * 删除旧的笔记项构建方法
   */

  /**
   * 构建笔记编辑器
   */
  Widget _buildNoteEditor() {
    final selectedNote = _notes.firstWhere(
      (note) => note.id == _selectedNoteId,
      orElse: () => _notes.first,
    );
    
    return MarkdownEditor(
      initialTitle: selectedNote.title,
      initialContent: selectedNote.content,
      onTitleChanged: (title) {
        setState(() {
          final index = _notes.indexWhere((note) => note.id == selectedNote.id);
          if (index != -1) {
            _notes[index] = _notes[index].copyWith(
              title: title,
              updatedAt: DateTime.now(),
            );
          }
        });
      },
      onContentChanged: (content) {
        setState(() {
          final index = _notes.indexWhere((note) => note.id == selectedNote.id);
          if (index != -1) {
            _notes[index] = _notes[index].copyWith(
              content: content,
              updatedAt: DateTime.now(),
            );
          }
        });
      },
    );
  }
}